package com.smtx.service.impl;

import com.smtx.service.FileService;
import com.smtx.service.Node;
import com.smtx.service.Repository;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Cyril
 * Date: 17.04.11
 * Time: 3:02
 * To change this template use File | Settings | File Templates.
 */
public class FileServiceImpl implements FileService {
    private Map<String, Repository> repositories = new HashMap<String, Repository>();
    private File basePath;

    @Override
    public Repository createRepository(String name) {
        if (!repositories.containsKey(name)) {
            try {
                repositories.put(name, new RepositoryImpl(
                        basePath.getAbsolutePath() + File.pathSeparator + name,
                        name));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return repositories.get(name);
    }

    @Override
    public Repository getRepository(String name) {
        return repositories.get(name);
    }

    @Override
    public Repository removeRepository(String name) {
        return removeRepository( getRepository(name) );
    }

    @Override
    public Repository removeRepository(Repository repository) {
        repository.remove();
        return repository;
    }

    @Override
    public Collection<Repository> listRepositories() {
        return repositories.values();
    }

    @Override
    public Node getNode(String reference) throws IOException {
        Repository.Reference ref = new RepositoryImpl.ReferenceImpl(reference);
        return getRepository(ref.getRepositoryName()).getNode(ref.getPath());
    }


}
